//
//  AESCryptor.swift
//  hrhtv
//
//  Created by Ink on 2025-08-08.
//

import Foundation
import CryptoSwift

public extension String {

    // AES/CBC/PKCS7Padding
    func decrypt_AES_ECB(key: String,ivs: String) -> String? {
        if let en = try? AESCryptor.decrypt_AES_CBC(decryptText: self, key: key, ivs: ivs) {
            return en
        }
        return nil
    }
    
    
    // AES/CBC/PKCS7Padding
    func encrypt_AES_CBC(key: String,ivs: String) -> String? {
        if let en = try? AESCryptor.encrypt_AES_CBC(encryptText: self, key: key, ivs: ivs) {
            return en
        }
        return nil
    }
    
    // AES/CBC/PKCS7Padding
    func decrypt_AES_CBC(key: String,ivs: String) -> String? {
        if let en = try? AESCryptor.decrypt_AES_CBC(decryptText: self, key: key, ivs: ivs) {
            return en
        }
        return nil
    }
    
}

public class AESCryptor: NSObject {
    
    /// AES_CBC 加密
    /// - Parameters:
    ///   - encryptText: 需要加密的数据
    ///   - key: 密钥
    ///   - ivs: 密钥偏移量
    /// - Returns: 加密后的数据
    static func encrypt_AES_CBC(encryptText: String, key: String, ivs: String) throws -> String {
        /// 使用AES_CBC模式
        let aes = try AES(key: Padding.noPadding.add(to: key.bytes, blockSize: AES.blockSize), blockMode: CBC(iv: ivs.bytes))

        /// 开始加密
        let encrypted = try aes.encrypt(encryptText.bytes)
        /// 将加密结果转成base64形式
        return encrypted.toBase64()
    }

    /// AES_CBC 解密
    /// - Parameters:
    ///   - decryptText: 需要解密的数据
    ///   - key: 秘钥
    ///   - ivs: 密钥偏移量
    /// - Returns: 解密后的数据
    static func decrypt_AES_CBC(decryptText: String, key: String, ivs: String) throws -> String {
        /// 使用AES_CBC模式
        let aes = try AES(key: Padding.noPadding.add(to: key.bytes, blockSize: AES.blockSize), blockMode: CBC(iv: ivs.bytes))
        /// 开始解密 从加密后的base64字符串解密
        let decrypted = try decryptText.decryptBase64ToString(cipher: aes)
        return decrypted
    }

    /// AES_GCM 加密
    /// - Parameters:
    ///   - encryptText: 需要加密的数据
    ///   - key: 密钥
    ///   - ivs: 密钥偏移量
    /// - Returns: 加密后的数据
    static func encrypt_AES_GCM(encryptText: Array<UInt8>, key: Array<UInt8>, ivs: Array<UInt8>) throws -> Array<UInt8> {
        let gcm = GCM(iv: ivs, mode: .combined)
        let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
        let encrypted = try aes.encrypt(encryptText)
        _ = gcm.authenticationTag
        return encrypted
    }

    /// AES_GCM 解密
    /// - Parameters:
    ///   - decryptText: 需要解密的数据
    ///   - key: 秘钥
    ///   - ivs: 密钥偏移量
    /// - Returns: 解密后的数据
    static func decrypt_AES_GCM(decryptText: Array<UInt8>, key: Array<UInt8>, ivs: Array<UInt8>) throws -> Array<UInt8> {
        let gcm = GCM(iv: ivs, mode: .combined)
        let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
        return try aes.decrypt(decryptText)
    }
}
